package 周赛;

import java.util.Arrays;

public class 获取单值网格的最小操作数 {

    public int minOperations(int[][] grid, int x) {
        int m = grid.length;
        int n = grid[0].length;
        int[] arr = new int[m * n];
        int idx=0;
        int sum=0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                arr[idx++]=grid[i][j];
            }
        }
        Arrays.sort(arr);
        //中位数
        int avg = arr[(m*n)/2];
        for (int i = 0; i < arr.length; i++) {
            int abs = Math.abs(arr[i] - avg);
            if (abs%x!=0)
                return -1;
            sum+=(abs/x);
        }
        return sum;
    }
}
